#!/usr/bin/ruby
require "rubygems"
require "nokogiri"
require "open-uri"

url = ARGV[0] # url = "http://www.douban.com/photos/album/45432109/"
if not url
  puts "Please input a douban album url!"
  exit
end

if not (/http:\/\/www.douban.com\/photos\/album\/\d+\// =~ url)
  puts "The url is invalid!"
  exit
end

puts "You are downloading douban pics form #{url}"

doc = Nokogiri::HTML(open(url))

folder_name = /\d+/.match(url).to_s + "_" + doc.css('h1').inner_text
sum = doc.css('.wr span.pl').inner_text.to_i
i, times, images = 0, sum/18, []


#get urls of douban pics
while i <= times do
  page = Nokogiri::HTML(open(url+"?start="+(i*18).to_s))
  page.css(".photo_wrap a img").each do |img|
    images << img.attribute("src").to_s.sub(/thumb/, "photo")
  end
  i += 1
end

#create folder
if not File.exist?(folder_name)
  puts "creating folder #{folder_name} ..."
  Dir::mkdir(folder_name)
end

#write to local disk
images.each_with_index do |img, i|
  regex = /p\d+\.jpg/
  dest = regex.match(img).to_s
  stream = open(img) { |f| f.read }
  output_file = File.join(folder_name, dest)
  open(output_file, "wb") do |f|
    puts "creating file #{output_file} from #{images[i]} ... #{i+1}/#{sum}"
    f.write(stream)
  end
end

